package com.skytech.ssr.dynamicdb.config;

import com.baomidou.dynamic.datasource.aop.DynamicAnnotationResolver;
import com.baomidou.mybatisplus.core.override.PageMapperProxy;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;

public class MyAnnotationResolver implements DynamicAnnotationResolver {
    @Override
    public Annotation resolve(MethodInvocation invocation, Class clzz) {
        /**
         * 场景1：DS注解在Service上，但Service方法中调用的是ServiceImpl的公有方法时
         */
        Class targetClass = invocation.getThis().getClass();
        Annotation annotation = targetClass.isAnnotationPresent(clzz) ? targetClass.getAnnotation(clzz) : null;

        if(annotation == null){
            /**
             * 场景2：DS注解在XXXMapper上，但Service方法发中调用的时ServiceImpl的共有方法时
             */
            targetClass = ((PageMapperProxy)Proxy.getInvocationHandler(((ReflectiveMethodInvocation) invocation).getThis())).getMapperInterface();
            annotation = targetClass.isAnnotationPresent(clzz) ? targetClass.getAnnotation(clzz) : null;
        }

        return annotation;
    }
}
